<template>
  <view class="yh-page">
	<view class="page">
		<view class="uni-column">
			<view class="yh-title">先执行登录,在登录状态下测试</view>
		</view>
		<view class="uni-form-item uni-column">
			<view class="title"><text class="red">*</text>用户id</view>
			<view class="uni-input-wrapper">
				<input class="uni-input" name="user_id" v-model="user_id" placeholder="请输入用户id"  @input="inputClearUserIdInput" />
				<text class="uni-icon" v-if="showClearUserIdIcon" @tap="handleToClearUserIdIcon">&#xe434;</text>
			</view>
			<button type="primary" @tap="handleToLoginByUserId()">执行登录</button>
		</view>
		<br/>
		<view class="uni-column">
			<view class="yh-title">测试websocket</view>
		</view>
		<view class="uni-form-item uni-column">
			<button type="primary" @tap="handleToSocketConnect()">socket连接</button>
		</view>
		<view v-show="connected" class="uni-form-item uni-column">
			<view class="yh-title">发送服务器返回的数据:{{showMsg}}</view>
			<button type="primary" @tap="handleToSocketSend()">测试socket发送数据</button>
		</view>
		<view v-show="connected" class="uni-form-item uni-column">
			<button type="primary" @tap="handleToSocketServerSend()">请求服务器发送</button>
		</view>
		<view class="uni-form-item uni-column">
			<button type="primary" @tap="handleToSocketClose()">关闭</button>
		</view>
	</view>
  </view>
</template>

<script>
import { loginByUserId }  from '@/api/test/login/wechat-login.js'
import { testWebsocket } from '@/api/test/socket/socket-server.js'
import { validNumber } from '@/utils/validate'
import { VUE_APP_HOST,VUE_APP_SOCKET_PORT } from '@/config/setting'
export default 
{
  //计算属性
  computed:
  {
	showMsg() {
		if (this.connected) 
		{
			if (this.msg) 
			{
				return '收到消息：' + this.msg
			} 
			else 
			{
				return '等待接收消息'
			}
		} 
		else 
		{
			return '尚未连接'
		}
	}
  },
  //监听
  watch:
  {

  },
  data() 
  {
    return{
		user_id:null,
		token:null,
		//控制是否显示清除user_id的图标
		showClearUserIdIcon:false,
		//socket链接状态
		connected: false,
		//socket是否正在链接
		connecting: false,
		socketTask: false,
		msg: false,
		serverMsg: false
    };
  },
  //页面加载
  onLoad() 
  {

  },
  //页面显示
  onShow() 
  {

  },
  //页面初次渲染完成
  onReady()
  {

  },
  //页面隐藏
  onHide()
  {

  },
  //页面卸载
  onUnload()
  {

  },
  methods:
  {
	//监听是否清除用户图标
	inputClearUserIdInput()
	{
	    if (this.user_id.length > 0) 
		{
	        this.showClearUserIdIcon = true;
	    } 
		else 
		{
	        this.showClearUserIdIcon = false;
	    }
	},
	//点击清除用户id
	handleToClearUserIdIcon() 
	{
	    this.inputUserId = null;
		this.user_id = null;
	    this.showClearUserIdIcon = false;
	},
	//用户id登录
	async handleToLoginByUserId()
	{
		let validatedNumber =  validNumber(this.user_id)
		
		if(!validatedNumber)
		{
			uni.showToast({
				image: "/static/test/notice/04-error.png",
				title: "必须是数字",
				mask:true,
				duration:2000
			})
			
			return 
		}
		
		let _this = this
		let param = {}
		param['user_id'] = this.user_id
		const result = await loginByUserId(param).then(res=>
		{
			return new Promise((resolve,reject)=>{
				if(res && res.code == 0)
				{
					
					resolve(res.data)
				}
			})
		})
		const {token,openid} = result
		
		if(token)
		{
			_this.$store.dispatch('user/loginSaveToken',token)
			
			if(openid)
			{
				_this.$store.dispatch('user/authSaveOpenid',openid)
			}
		}
		
	},
	//执行socket连接
	handleToSocketConnect()
	{
		if (this.connected || this.connecting) 
		{
			uni.showModal({
				content: '正在连接或者已经连接，请勿重复连接',
				showCancel: false
			})
			return false
		}
		
		this.connecting = true
		
		uni.showLoading({
			title: '连接中...'
		})
		
		let _this = this
		
		this.socketTask = uni.connectSocket({
			//url: 'ws://api.youhujun.com:8080', //仅为示例，并非真实接口地址。
			url: 'ws://'+ VUE_APP_HOST +':'+ VUE_APP_SOCKET_PORT,
			//#ifdef MP
			header: {
				'content-type': 'application/json'
			},
			//#endif
			//#ifdef MP-WEIXIN
			method: 'GET',
			//#endif
			success:()=>{
				console.log('connect');
				
			},
			complete: ()=> {}
		})
		console.log(_this.socketTask);
		this.socketTask.onOpen((res)=>
		{
			console.log('connect open');
			this.connecting = false
			this.connected = true
			uni.hideLoading()
			uni.showToast({
				icon: 'none',
				title: '连接成功'
			})
		});
		this.socketTask.onError((err) => {
			this.connecting = false
			this.connected = false
			uni.hideLoading()
			uni.showModal({
				content: '连接失败，可能是websocket服务不可用，请稍后再试',
				showCancel: false
			})
			console.log('onError', err);
		})
		
		this.socketTask.onMessage((res) =>
		{
			console.log('onMessage', res)
			
			let data = JSON.parse(res.data)
			
			console.log('data', data)
			
			this.msg = data.msg
		})
		
		this.socketTask.onClose((res) => {
			this.connected = false
			this.socketTask = false
			this.msg = false
			console.log('onClose', res)
		})
	},
	//发送消息
	handleToSocketSend()
	{
		console.log('测试socket发送数据')
		
		let param = {};
		
		param['user_id'] = this.user_id;
		
		param['token'] = this.$store.getters.token;
		
		param['type'] = 10;
		
		param = JSON.stringify(param) 
	
		this.socketTask.send({
			data: param,
			success(res) 
			{
				console.log(res);
			},
			fail(err) 
			{
				console.log(err);
			}
		})
	},
	//请求服务器主动发送数据
	handleToSocketServerSend()
	{
		let param = {}
		param['user_id'] = this.user_id
		param['send_type'] = 20
		param['event'] = 10
		
		testWebsocket(param).then(res=>{
			//console.log(res)
		})
	},
	//关闭
	handleToSocketClose()
	{
		console.log('关闭socket链接')
		if (this.socketTask && this.socketTask.close) 
		{
			this.socketTask.close()
		}
	}
  }

}
</script>

<style lang="scss" scoped>
.page{
	width:calc(100% - 70rpx);
	padding:35rpx;
}
.title {
        padding: 5rpx 13rpx;
    }

.uni-input-wrapper {
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
	flex-direction: row;
	flex-wrap: nowrap;
	background-color: #FFFFFF;
}

.uni-input {
	height: 80rpx;
	line-height: 80rpx;
	font-size: 36rpx;
	padding: 0rpx;
	flex: 1;
	background-color: #FFFFFF;
}

.uni-icon {
	font-family: uniicons;
	font-size: 80rpx;
	font-weight: normal;
	font-style: normal;
	width: 80rpx;
	height: 80rpx;
	line-height: 80rpx;
	color: #999999;
}

.red{
	color:red;
	font-weight: true;
}
</style>
